package cn.wh.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import cn.wh.beans.BeansException;
import cn.wh.beans.factory.DisposableBean;
import cn.wh.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * @author: wh
 * @create: 2022-09-20 14:27
 * @description
 **/
public class DisposableBeanAdapter implements DisposableBean {

    private final Object bean;

    private final String beanName;

    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        // 1. 实现接口 DisposableBean
        if (bean instanceof DisposableBean){
            ((DisposableBean) bean).destroy();
        }
        // 2. 注解配置 destroy-method {判断是为了避免二次执行销毁}
        if (StrUtil.isNotEmpty(destroyMethodName)&&!(bean instanceof DisposableBean && "destory".equals(this.destroyMethodName))){
            Method destoryMethod=bean.getClass().getMethod(destroyMethodName);
            if (destoryMethod==null){
                throw new BeansException("Couldn't find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'");
            }
            destoryMethod.invoke(bean);
        }
    }
}
